/**
 * 字符串扩展
 */

// 标签模板
const name = 'tom'
const gender = 'man'

// 标签模板拼接
function myTagFunc (strings, ...values) {
  console.log(strings, values)
  let len = values.length
  let res = ''
  for (let i = 0; i < len; i++) {
    res = res + strings[i] + values[i]
  }
  res += strings[len]
  return res
}

let res = myTagFunc`hey, ${name} is a ${gender}.`
console.log(res)

// 用标签模板过滤用户输入的字符，防止xss攻击

const msg = '<script src="xxx.php"></script>'

function encodeHtml (html='') {
  return html.replace(/&/g, "&amp;")
             .replace(/</g, "&lt;")
             .replace(/>/g, "&gt;");
}

function SaferHTML(strings, ...values) {
  let len = values.length
  let res = ''
  for (let i = 0; i < len; i++) {
    res = res + strings[i] + encodeHtml(values[i])
  }
  res += strings[len]
  return res
}

const message = SaferHTML`<p>用户输入了${msg}</p>`;
console.log(message)


// 字符串扩展方法----------------------

const str = 'Error: foo is not defined.'

console.log(str.startsWith('Error'))
console.log(str.endsWith('.'))
console.log(str.includes('foo'))
